package com.easy.web.controller;

import com.easy.web.utils.DateUtil;
import com.easy.web.utils.ViewUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2016/12/5.
 */
@Controller
@RequestMapping("file")
public class UpLoadController {

    private static Logger logger = LoggerFactory.getLogger(UpLoadController.class);

    /**
     * 图片上传保存接口
     * 聊天
     * ajax
     */
    @RequestMapping(value = "upload", method = {RequestMethod.POST})
    public ModelAndView savePic(@RequestParam(value = "upImg", required = false) MultipartFile[] files, HttpServletRequest request) {
        String resultPath = "";
        try {
            String dateStr = DateUtil.getCurrentDate();
            resultPath = importFiles(files, "upload/chat" + dateStr, request);
        } catch (Exception e) {
            return new ModelAndView("", ViewUtils.mapFail("上传失败，请重新上传！"));
        }

        return new ModelAndView("", ViewUtils.mapSuccess(resultPath));

    }

    /**
     * 系统图片上传保存接口
     * ajax
     */
    @RequestMapping(value = "sysUpload", method = {RequestMethod.POST})
    public ModelAndView SysUpload(@RequestParam(value = "upImg", required = false) MultipartFile[] files, HttpServletRequest request) {
        String resultPath = "";
        try {
            resultPath = importFiles(files, "upload/sysLogo", request);
        } catch (Exception e) {
            return new ModelAndView("", ViewUtils.mapFail("上传失败，请重新上传！"));
        }

        return new ModelAndView("", ViewUtils.mapSuccess(resultPath));

    }

    /**
     * 幻灯片图片上传保存接口
     * ajax
     */
    @RequestMapping(value = "slideUpload", method = {RequestMethod.POST})
    public ModelAndView SlideUpload(@RequestParam(value = "upImg", required = false) MultipartFile[] files, HttpServletRequest request) {
        String resultPath = "";
        try {
            resultPath = importFiles(files, "upload/sysSlide", request);
        } catch (Exception e) {
            return new ModelAndView("", ViewUtils.mapFail("上传失败，请重新上传！"));
        }

        return new ModelAndView("", ViewUtils.mapSuccess(resultPath));

    }

    /**
     * 海报图
     * @param files
     * @param request
     * @return
     */
    @RequestMapping(value = "posterImg", method = {RequestMethod.POST})
    public ModelAndView PosterImgUpload(@RequestParam(value = "upImg", required = false) MultipartFile[] files, HttpServletRequest request) {
        String resultPath = "";
        try {
            resultPath = importFiles(files, "upload/poster", request);
        } catch (Exception e) {
            return new ModelAndView("", ViewUtils.mapFail("上传失败，请重新上传！"));
        }

        return new ModelAndView("", ViewUtils.mapSuccess(resultPath));

    }

    /**
     * 课程图片上传保存接口
     * ajax
     */
    @RequestMapping(value = "courseUpload", method = {RequestMethod.POST})
    public ModelAndView courseUpload(@RequestParam(value = "upImg", required = false) MultipartFile[] files, HttpServletRequest request) {
        String resultPath = "";
        try {
            resultPath = importFiles(files, "upload/sysCourse", request);
        } catch (Exception e) {
            return new ModelAndView("", ViewUtils.mapFail("上传失败，请重新上传！"));
        }

        return new ModelAndView("", ViewUtils.mapSuccess(resultPath));

    }

    /**
     * 文章封面图片上传保存接口
     * ajax
     */
    @RequestMapping(value = "articleUpload", method = {RequestMethod.POST})
    public ModelAndView articleUpload(@RequestParam(value = "upImg", required = false) MultipartFile[] files, HttpServletRequest request) {
        String resultPath = "";
        try {
            resultPath = importFiles(files, "upload/sysArticle", request);
        } catch (Exception e) {
            return new ModelAndView("", ViewUtils.mapFail("上传失败，请重新上传！"));
        }

        return new ModelAndView("", ViewUtils.mapSuccess(resultPath));

    }


    /**
     * 保存上传的文件
     *
     * @param files
     * @param request
     * @return
     */
    private String importFiles(MultipartFile[] files, String mkName, HttpServletRequest request) throws IOException {
        String resultStr = "";
        for (MultipartFile file : files) {
            String path = request.getSession().getServletContext().getRealPath("/");
            logger.info("----------path------------:" + path);
            String fileName = file.getOriginalFilename();
            String prefix = ".jpg";//默认
            if (fileName.lastIndexOf(".") > 0) {
                prefix = fileName.substring(fileName.lastIndexOf("."));
            }
            fileName = new Date().getTime() + prefix;
            File targetFile = new File(path + mkName, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            file.transferTo(targetFile);
            resultStr = "/" + mkName + "/" + fileName;

        }
        return resultStr;
    }

    /**
     * 图片上传
     * form
     */
    @RequestMapping(value = "formUpload", method = {RequestMethod.POST})
    public String saveFormPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        File filePath = new File(request.getSession().getServletContext().getRealPath("upload"));
        factory.setRepository(filePath);

        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown
        upload.setSizeMax(1000000 * 20);//设置缓冲区

        String resultStr = "";
        try {

            List fileItems = upload.parseRequest(request);

            String itemNo = "";
            //Iterator iter = fileItems.iterator()取其迭代器
            //iter.hasNext()检查序列中是否还有元素
            for (Iterator iter = fileItems.iterator(); iter.hasNext(); ) {
                //获得序列中的下一个元素
                FileItem item = (FileItem) iter.next();


                //判断是文件还是文本信息
                //是普通的表单输入域
                if (item.isFormField()) {
                    if ("itemNo".equals(item.getFieldName())) {
                        itemNo = item.getString();
                    }
                }
                //是否为input="type"输入域
                if (!item.isFormField()) {
                    //上传文件的名称和完整路径
                    String fileName = item.getName();

                    long size = item.getSize();
                    //判断是否选择了文件
                    if ((fileName == null || fileName.equals("")) && size == 0) {
                        continue;
                    }
                    String prefix = fileName.substring(fileName.lastIndexOf("."));
                    fileName = new Date().getTime() + prefix;

                    // 保存文件在服务器的物理磁盘中：第一个参数是：完整路径（不包括文件名）第二个参数是：文件名称
                    //item.write(file);
                    //修改文件名和物料名一致，且强行修改了文件扩展名为gif
                    //item.write(new File(uploadPath, itemNo + ".gif"));
                    //将文件保存到目录下，不修改文件名
                    item.write(new File(filePath, fileName));
                    resultStr = "/upload/" + fileName;
                }
            }
        } catch (Exception e) {
//            return new ModelAndView("", ViewUtils.mapFail("上传失败，请重新上传！"));
        }
        response.setContentType("text/xml");
        response.getWriter().print(resultStr);
        return null;

    }

}
